package com.irdstudio.devops.agent.plugin.mysql;

import com.irdstudio.bfp.executor.core.plugin.AbstractPlugin;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * MySQL数据库备份
 *
 * @author GaoHuanjie
 */
public class MysqlBackupPlugin extends AbstractPlugin {
    private String pluginName = null;
    PluginMysqlBackupConf pluginParam=null;

    @Override
    protected boolean doReadConfigureFromDB(Connection connection, String s) throws SQLException {
        pluginName = context.getSzPluginName();
        pluginParam = context.getSzPluginParam(PluginMysqlBackupConf.class);
        if (pluginParam==null)
        {
            context.setSzLastErrorMsg("未读取到配置标识为：" + s + "的数据MySQL配置!");
            return false;
        }else {
            return true;
        }
    }

    @Override
    public boolean execute() throws Exception {
         String baseIP;
         String userName;
         String password;
         String savePath;
         String databaseName;
         boolean flag = true;

         baseIP = pluginParam.getBaseIP();
         userName = pluginParam.getUserName();
         password = pluginParam.getPassword();
         savePath = pluginParam.getSavePath();
         databaseName = pluginParam.getDatabaseName();

        File saveFile = new File(savePath+"/"+databaseName);
        String time= new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        if (!saveFile.exists()) {// 如果目录不存在
            saveFile.mkdirs();// 创建文件夹
        }
        if (!savePath.endsWith(File.separator)) {
            savePath = savePath + File.separator;
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("mysqldump").append(" --column-statistics=0").append(" --opt").append(" -h").append(baseIP);
        stringBuilder.append(" --user=").append(userName).append(" --password=").append(password).append(" --lock-all-tables=true");
        stringBuilder.append(" --result-file=").append(savePath +"/"+databaseName+ "/"+time+".sql").append(" --default-character-set=utf8 ").append(databaseName);
        System.out.println("开始备份：" + stringBuilder);
        logger.info("开始备份，执行命令："+stringBuilder);

        try {
            Process process = Runtime.getRuntime().exec(""+stringBuilder.toString());
            if (process.waitFor() == 0) {// 0 表示线程正常终止。
                flag = true;
                return flag;
            }
        } catch (IOException e) {
            flag =false;
            logger.error(e);
            e.printStackTrace();

        } catch (InterruptedException e) {
            flag =false;
            logger.error(e);
            e.printStackTrace();
        }
        flag=false;
        return flag;
    }

}